import Axios from 'axios';
import { Exception } from './error';
import codes from 'data/code';

export function is_reply(obj) {
  if (typeof obj !== 'object') {
    return false;
  }
  if (!obj.hasOwnProperty('code') || !obj.hasOwnProperty('message')) {
    return false;
  }
  return true;
}

export default class API {

  static request(method, url, data, type) {
    return new Promise(function (resolve, reject) {
  
      let config = { method: method, url: url, data: data,headers:{userId: "1"}};
      let formData = new FormData();
      if (type === 'form') {
        Object.keys(data).map(item => {
          formData.append(item, data[item])
        })
        config.data = formData;
      }

      Axios.request(config).then(function (res) {
        console.log(res, 'Axios-suc')
        const reply = res.data;
        if (!is_reply(reply)) {
          reject(reply);
        }

        if (reply.code === codes.ok) {
          resolve(reply);
        } else {
          reject(reply);
        }
      }).catch(function (err) {
        console.log(err, 'Axios-catch')
        let code = -1;
        const { response } = err;
        if (response) {
          code = response.status;
        }
        reject(err);
      })
    });
  }

  static get(url) {
    return API.request('get', url);
  }

  static post(url, params, type) {
    return API.request('post', url, params, type);
  }

  static put(url, params, type) {
    return API.request('put', url, params, type);
  }

  static delete(url, params) {
    return API.request('delete', url, params);
  }

  static invoke(func) {
    return new Promise(function (resolve, reject) {
      func();
      resolve();
    });
  }

  static delay(time) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve();
      }, time);
    })
  }
}